<?

class login extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->model('user_model');
    }

    public function index() {
        $this->load->helper('form', 'url');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('user', 'User', '');

        if ($this->form_validation->run() === FALSE) {
            if ($this->session->userdata('user_id')!=null) {
                $this->checkType($this->session->userdata('type'));
            } else {
                $data['title'] = 'Login Page';
                $this->load->view('login', $data);
                $this->load->view('templates/footer');
            }
        } else {
            $data = $this->checkUser();
            if (!empty($data)) {
                $session_data = array('user_id' => $data['user_id'], 'username' => $data['username'], 'type' => $data['type']);
                $this->user_model->removeOtherLogin($data['username']);
                $this->session->set_userdata($session_data);
                  $this->user_model->removeBlankSession();
                $this->checkType($data['type']);
            } else {
                $data['error'] = 'Wrong username or password';
                $data['title'] = 'Login Page';
                $this->load->view('login', $data);
                $this->load->view('templates/footer');
            }
        }
    }

    public function checkUser() {
        $login = array(
            'user' => $this->input->post('user'),
            'password' => $this->input->post('password')
        );
        $data = $this->user_model->getUser($login['user'], $login['password']);
        return $data;
    }

    public function checkType($type) {
        if ($type == 'moderator') {
            $location = base_url('moderator/dashboard/');
        } else if ($type == 'student') {
            $location = base_url('student/display/');
        } else if ($type == 'administrator') {
            $location = base_url('admin/dashboard/');
        }

        redirect($location);
    }

}

?>